import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { 
  Brain, MessageCircle, Target, ArrowRight, Cat, 
  FileText, Edit, Eye, Download, CheckCircle, 
  BarChart3, Lightbulb, Quote, PieChart,
  Book, Plus, GripVertical, Zap, X
} from "lucide-react";
import { useState } from "react";

const templateOptions = [
  { 
    id: "lab-report", 
    label: "Lab Report", 
    sections: ["Hypothesis", "Methodology", "Results", "Conclusion"] 
  },
  { 
    id: "essay", 
    label: "5-Paragraph Essay", 
    sections: ["Introduction", "Body Paragraph 1", "Body Paragraph 2", "Body Paragraph 3", "Conclusion"] 
  },
  { 
    id: "research-proposal", 
    label: "Research Proposal", 
    sections: ["Abstract", "Literature Review", "Methodology", "Timeline"] 
  },
  { 
    id: "presentation", 
    label: "Presentation Outline", 
    sections: ["Opening", "Main Points", "Supporting Evidence", "Closing"] 
  }
];

const smartBlocks = [
  { 
    id: "argument", 
    label: "Argument Block", 
    icon: Target, 
    color: "bg-blue-50 border-blue-300 hover:bg-blue-100 text-blue-700", 
    description: "Claim, reasoning, and evidence"
  },
  { 
    id: "data", 
    label: "Data Interpretation", 
    icon: BarChart3, 
    color: "bg-green-50 border-green-300 hover:bg-green-100 text-green-700", 
    description: "Analyze figures or datasets"
  },
  { 
    id: "counterpoint", 
    label: "Counterpoint", 
    icon: MessageCircle, 
    color: "bg-orange-50 border-orange-300 hover:bg-orange-100 text-orange-700", 
    description: "Present an opposing view"
  },
  { 
    id: "citation", 
    label: "Citation", 
    icon: Quote, 
    color: "bg-purple-50 border-purple-300 hover:bg-purple-100 text-purple-700", 
    description: "Formatted academic reference"
  }
];

const qualityMetrics = [
  { label: "Clarity", score: 78, color: "bg-blue-500" },
  { label: "Coherence", score: 85, color: "bg-green-500" },
  { label: "Academic Voice", score: 72, color: "bg-purple-500" },
  { label: "Task Relevance", score: 90, color: "bg-orange-500" }
];

const getAISuggestions = (sectionType: string, topic: string) => {
  const suggestions: Record<string, string> = {
    // Lab Report suggestions
    "Hypothesis": topic 
      ? `Formulate a testable hypothesis about ${topic}. Consider what specific outcome you expect and why.`
      : "Formulate a testable hypothesis. Consider what specific outcome you expect and why.",
    "Methodology": topic
      ? `Describe your experimental approach for studying ${topic}. Include materials, procedures, and controls.`
      : "Describe your experimental approach. Include materials, procedures, and controls.",
    "Results": topic
      ? `Present your findings about ${topic}. Use data, charts, and observations to support your conclusions.`
      : "Present your findings. Use data, charts, and observations to support your conclusions.",
    "Conclusion": topic
      ? `Summarize what your results reveal about ${topic} and discuss broader implications.`
      : "Summarize what your results reveal and discuss broader implications.",
    
    // Essay suggestions
    "Introduction": topic
      ? `Start with a compelling hook about ${topic}, provide background context, and end with a clear thesis statement.`
      : "Start with a compelling hook, provide background context, and end with a clear thesis statement.",
    "Body Paragraph 1": topic
      ? `Present your strongest argument about ${topic}. Use evidence and examples to support your main point.`
      : "Present your strongest argument. Use evidence and examples to support your main point.",
    "Body Paragraph 2": topic
      ? `Develop your second key point about ${topic}. Connect it to your thesis with smooth transitions.`
      : "Develop your second key point. Connect it to your thesis with smooth transitions.",
    "Body Paragraph 3": topic
      ? `Address counterarguments or provide additional evidence about ${topic} to strengthen your position.`
      : "Address counterarguments or provide additional evidence to strengthen your position.",
    
    // Research Proposal suggestions
    "Abstract": topic
      ? `Provide a concise summary of your proposed research on ${topic}. Include purpose, methods, and expected outcomes.`
      : "Provide a concise summary of your proposed research. Include purpose, methods, and expected outcomes.",
    "Literature Review": topic
      ? `Summarize existing research on ${topic}. Identify gaps your study will address.`
      : "Summarize existing research. Identify gaps your study will address.",
    "Timeline": topic
      ? `Create a realistic timeline for completing your ${topic} research project.`
      : "Create a realistic timeline for completing your research project.",
    
    // Presentation suggestions
    "Opening": topic
      ? `Grab attention with a compelling question or statistic about ${topic}. Introduce yourself and preview your main points.`
      : "Grab attention with a compelling question or statistic. Introduce yourself and preview your main points.",
    "Main Points": topic
      ? `Organize 3-5 key points about ${topic}. Use clear headings and supporting evidence for each.`
      : "Organize 3-5 key points. Use clear headings and supporting evidence for each.",
    "Supporting Evidence": topic
      ? `Include relevant data, examples, and visuals that support your points about ${topic}.`
      : "Include relevant data, examples, and visuals that support your points.",
    "Closing": topic
      ? `Summarize your key findings about ${topic} and end with a call to action or thought-provoking question.`
      : "Summarize your key findings and end with a call to action or thought-provoking question."
  };
  
  return suggestions[sectionType] || "Start writing your content here...";
};

const generateSmartBlockContent = (blockType: string, topic: string) => {
  const topicPrompt = topic ? `You are writing about: "${topic}". Please keep all generated content closely relevant to this topic.` : "";
  
  switch (blockType) {
    case "argument":
      return {
        prompt: `Write a structured paragraph that presents a clear argument about "${topic || 'your topic'}". Include a strong claim, one supporting reason, and one piece of evidence. Use academic tone but keep it concise and easy to follow.`,
        content: topic 
          ? `**Claim:** ${topic} represents a critical issue that demands immediate attention. **Reasoning:** Research consistently demonstrates that [specific evidence related to ${topic}], which supports the argument that [clear position]. **Evidence:** This evidence is particularly compelling because it [reasoning that connects evidence to claim], highlighting the urgent need for [relevant action or conclusion].`
          : `**Claim:** [Your topic] represents a critical issue that demands immediate attention. **Reasoning:** Research consistently demonstrates that [specific evidence], which supports the argument that [clear position]. **Evidence:** This evidence is particularly compelling because it [reasoning that connects evidence to claim], highlighting the urgent need for [relevant action or conclusion].`
      };
    
    case "data":
      return {
        prompt: `Based on the topic "${topic || 'your topic'}", write a short paragraph interpreting a dataset, graph, or trend. Explain the insight clearly and mention its implication in one or two sentences.`,
        content: topic
          ? `**Data Pattern:** Recent analysis reveals significant trends in ${topic}. **Key Finding:** The data shows a [describe trend/pattern] over the past [time period], with [specific metrics or percentages]. **Interpretation:** This pattern suggests that [interpretation of what the data means], which has important implications for [relevant field or stakeholders]. **Significance:** These insights indicate that [broader significance or future predictions].`
          : `**Data Pattern:** Recent analysis reveals significant trends in [your topic]. **Key Finding:** The data shows a [describe trend/pattern] over the past [time period], with [specific metrics or percentages]. **Interpretation:** This pattern suggests that [interpretation of what the data means], which has important implications for [relevant field or stakeholders].`
      };
    
    case "counterpoint":
      return {
        prompt: `Write a paragraph presenting an opposing view on "${topic || 'your topic'}". Clearly explain the reasoning behind this view and how it challenges the main argument. Maintain a neutral tone.`,
        content: topic
          ? `**Opposition Stance:** However, critics of the prevailing view on ${topic} argue that [opposing position]. **Counter-reasoning:** They contend that [reasoning behind opposition], citing [evidence or examples that support the counterpoint]. **Challenge to Main View:** This perspective challenges the mainstream argument by suggesting that [how it undermines the main position]. **Complexity:** While this viewpoint raises valid concerns about [specific issues], it also highlights the complexity of [relevant aspects of the topic].`
          : `**Opposition Stance:** However, critics of the prevailing view argue that [opposing position]. **Counter-reasoning:** They contend that [reasoning behind opposition], citing [evidence or examples that support the counterpoint]. **Challenge to Main View:** This perspective challenges the mainstream argument by suggesting that [how it undermines the main position].`
      };
    
    case "citation":
      return {
        prompt: `Generate one APA-style academic citation related to "${topic || 'your topic'}". Use a real or plausible source such as a journal article, government report, or expert-authored book.`,
        content: topic
          ? `Johnson, M. A., & Smith, K. L. (2024). Contemporary perspectives on ${topic}: A comprehensive analysis. *Journal of Advanced Research*, 45(3), 234-251. https://doi.org/10.1080/jar.2024.123456\n\n**How to use:** This citation can be placed in your reference list and cited in-text as (Johnson & Smith, 2024).`
          : `Author, A. A. (Year). Title of the work related to your topic. *Journal Name*, Volume(Issue), pages. https://doi.org/10.xxxx/xxxxx\n\n**How to use:** Replace with actual source information and cite in-text as (Author, Year).`
      };
    
    default:
      return {
        prompt: "Generate relevant content for this block type.",
        content: "Content will be generated based on your selection."
      };
  }
};

export function SmartWritingCanvas() {
  const [selectedTemplate, setSelectedTemplate] = useState("lab-report");
  const [canvasView, setCanvasView] = useState("structure");
  const [completeness, setCompleteness] = useState(45);
  const [mirrorAgentOpen, setMirrorAgentOpen] = useState(false);
  const [topic, setTopic] = useState("");
  const [generatedContent, setGeneratedContent] = useState<{type: string, content: string, prompt: string} | null>(null);

  const currentTemplate = templateOptions.find(t => t.id === selectedTemplate);
  const sections = currentTemplate?.sections || [];

  const handleTemplateSelect = (templateId: string) => {
    setSelectedTemplate(templateId);
  };

  const addSmartBlock = (blockType: string) => {
    console.log(`Adding ${blockType} smart block`);
    // Clear previous content first, then generate new content
    setGeneratedContent(null);
    const generated = generateSmartBlockContent(blockType, topic);
    setGeneratedContent({
      type: blockType,
      content: generated.content,
      prompt: generated.prompt
    });
  };

  const exportDocument = (format: string) => {
    console.log(`Exporting document as ${format}`);
  };

  const closeGeneratedContent = () => {
    setGeneratedContent(null);
  };

  return (
    <TooltipProvider>
      <div className="space-y-8">
        {/* Smart Writing Canvas Header */}
        <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-2xl p-6">
          <div className="text-center mb-6">
            <Brain className="w-10 h-10 mx-auto mb-3 text-blue-600" />
            <h3 className="text-xl font-bold text-blue-900 mb-2">Smart Writing Canvas</h3>
          </div>
          
          {/* Horizontal Tab Bar */}
          <div className="flex justify-center">
            <div className="inline-flex bg-white rounded-lg p-1 shadow-sm border border-blue-200">
              {templateOptions.map((template) => (
                <button
                  key={template.id}
                  onClick={() => handleTemplateSelect(template.id)}
                  className={`px-4 py-2 text-sm font-medium rounded-md transition-all duration-200 whitespace-nowrap ${
                    selectedTemplate === template.id
                      ? 'bg-blue-600 text-white shadow-sm'
                      : 'text-blue-700 hover:bg-blue-50'
                  }`}
                >
                  {template.label}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Canvas Interface */}
        <div className="space-y-6">
          {/* Canvas Header */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Badge className="bg-blue-100 text-blue-700">
                {currentTemplate?.label}
              </Badge>
              <div className="flex items-center gap-2">
                <Zap className="w-4 h-4 text-yellow-500" />
                <Badge variant="secondary" className="bg-yellow-50 text-yellow-700 border-yellow-200">
                  🎯 Critical Thinking Focus
                </Badge>
              </div>
            </div>
            
            <div className="flex items-center gap-3">
              <Select value={canvasView} onValueChange={setCanvasView}>
                <SelectTrigger className="w-40">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="structure">Structure View</SelectItem>
                  <SelectItem value="freewrite">Free Write View</SelectItem>
                </SelectContent>
              </Select>
              
              <Button
                variant="outline"
                size="sm"
                onClick={() => setMirrorAgentOpen(!mirrorAgentOpen)}
                className="border-orange-300 text-orange-700 hover:bg-orange-50"
              >
                <Cat className="w-4 h-4 mr-2" />
                Mirror Agent
              </Button>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
            {/* Main Canvas */}
            <div className="lg:col-span-3 space-y-6">
              {/* Topic Input Bar - Moved above progress */}
              <Card className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border-2 border-blue-200">
                <div className="flex items-center gap-3">
                  <Lightbulb className="w-5 h-5 text-blue-600 flex-shrink-0" />
                  <div className="flex-1">
                    <label className="block text-sm font-medium text-blue-900 mb-2">
                      You are writing about:
                    </label>
                    <Input
                      placeholder="Enter your topic to personalize AI suggestions..."
                      value={topic}
                      onChange={(e) => setTopic(e.target.value)}
                      className="bg-white border-blue-300 focus:border-blue-500 focus:ring-blue-500"
                    />
                  </div>
                </div>
              </Card>

              {/* Progress Bar - Now below topic input */}
              <Card className="p-4 rounded-xl shadow-sm">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm font-medium text-gray-700">Progress</span>
                  <span className="text-sm text-gray-600">{completeness}% Complete</span>
                </div>
                <Progress value={completeness} className="mb-3" />
                
                {/* Quality Indicators */}
                <div className="grid grid-cols-4 gap-3">
                  {qualityMetrics.map((metric) => (
                    <div key={metric.label} className="text-center">
                      <div className="text-xs text-gray-600 mb-1">{metric.label}</div>
                      <div className="flex items-center justify-center">
                        <div className={`w-8 h-2 rounded-full ${metric.color}`} style={{ width: `${metric.score}%` }}></div>
                        <span className="text-xs ml-1">{metric.score}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </Card>

              {/* Generated Content Display */}
              {generatedContent && (
                <Card className="p-6 bg-gradient-to-br from-green-50 to-emerald-50 border-2 border-green-200 shadow-lg">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <h4 className="text-lg font-semibold text-green-900 capitalize mb-1">
                        {generatedContent.type.replace('-', ' ')} Generated
                      </h4>
                      <p className="text-sm text-green-700 mb-3">
                        <strong>Prompt used:</strong> {generatedContent.prompt}
                      </p>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={closeGeneratedContent}
                      className="text-green-600 hover:text-green-800 hover:bg-green-100"
                    >
                      <X className="w-4 h-4" />
                    </Button>
                  </div>
                  <div className="bg-white rounded-lg p-4 border border-green-200">
                    <p className="text-gray-800 leading-relaxed whitespace-pre-wrap">
                      {generatedContent.content}
                    </p>
                  </div>
                  <div className="flex gap-2 mt-4">
                    <Button size="sm" className="bg-green-600 hover:bg-green-700">
                      Insert into Document
                    </Button>
                    <Button variant="outline" size="sm" className="border-green-300 text-green-700">
                      Regenerate
                    </Button>
                    <Button variant="outline" size="sm" className="border-green-300 text-green-700">
                      Copy Text
                    </Button>
                  </div>
                </Card>
              )}

              {/* Writing Sections */}
              <div className="space-y-4">
                {sections.map((section, index) => (
                  <Card key={section} className="rounded-xl shadow-sm border-2 border-gray-100 hover:border-blue-200 transition-colors bg-white">
                    <CardHeader className="pb-3">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <GripVertical className="w-4 h-4 text-gray-400" />
                          <CardTitle className="text-lg font-semibold text-gray-900">{section}</CardTitle>
                        </div>
                        <div className="flex items-center gap-2">
                          <Button variant="ghost" size="sm" className="text-gray-500 hover:text-blue-600">
                            <Lightbulb className="w-4 h-4" />
                          </Button>
                          <Button variant="ghost" size="sm" className="text-gray-500 hover:text-blue-600">
                            <Eye className="w-4 h-4" />
                          </Button>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent className="pt-0">
                      {/* AI Suggestion */}
                      <div className="mb-3 p-3 bg-blue-50 rounded-lg border border-blue-100">
                        <div className="flex items-start gap-2">
                          <Brain className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
                          <p className="text-sm text-blue-800">{getAISuggestions(section, topic)}</p>
                        </div>
                      </div>
                      
                      <Textarea
                        placeholder={`Start writing your ${section.toLowerCase()}...`}
                        className="min-h-32 resize-none border-gray-200 focus:border-blue-500 focus:ring-blue-500"
                      />
                      <div className="flex items-center justify-between mt-3 pt-3 border-t border-gray-100">
                        <div className="flex items-center gap-2">
                          <CheckCircle className="w-4 h-4 text-green-500" />
                          <span className="text-xs text-gray-600">AI suggestions available</span>
                        </div>
                        <Button variant="ghost" size="sm" className="text-orange-600 hover:text-orange-700 hover:bg-orange-50">
                          <Cat className="w-4 h-4 mr-1" />
                          Get Help
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>

              {/* Export Options */}
              <Card className="p-4 rounded-xl shadow-sm bg-gray-50">
                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="font-medium text-gray-900">Ready to submit?</h4>
                    <p className="text-sm text-gray-600">Export your work in multiple formats</p>
                  </div>
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" onClick={() => exportDocument('pdf')} className="border-gray-300">
                      <Download className="w-4 h-4 mr-2" />
                      PDF
                    </Button>
                    <Button variant="outline" size="sm" onClick={() => exportDocument('word')} className="border-gray-300">
                      <Download className="w-4 h-4 mr-2" />
                      Word
                    </Button>
                    <Button size="sm" className="bg-blue-600 hover:bg-blue-700">
                      Submit Online
                    </Button>
                  </div>
                </div>
              </Card>
            </div>

            {/* Sidebar */}
            <div className="space-y-6">
              {/* Mirror Agent Panel */}
              {mirrorAgentOpen && (
                <Card className="border-orange-200 bg-gradient-to-br from-orange-50 to-pink-50 rounded-xl shadow-sm">
                  <CardHeader className="pb-3">
                    <CardTitle className="text-lg flex items-center gap-2 text-orange-700">
                      <Cat className="w-5 h-5" />
                      Mirror Agent
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="bg-white rounded-lg p-3 border border-orange-100">
                      <p className="text-sm text-gray-800">💡 Your introduction could benefit from a stronger thesis statement. Try being more specific about your main argument.</p>
                    </div>
                    <div className="bg-white rounded-lg p-3 border border-orange-100">
                      <p className="text-sm text-gray-800">📊 Consider adding data or evidence to support your second paragraph's claims.</p>
                    </div>
                    <Button size="sm" className="w-full bg-orange-500 hover:bg-orange-600 text-white">
                      <MessageCircle className="w-4 h-4 mr-2" />
                      Ask Mirror Agent
                    </Button>
                  </CardContent>
                </Card>
              )}

              {/* AI Smart Blocks - New Horizontal Tag Design */}
              <Card className="rounded-xl shadow-sm">
                <CardHeader className="pb-4">
                  <CardTitle className="text-lg">AI Smart Blocks</CardTitle>
                  <CardDescription className="text-sm">Enhance your writing with guided blocks</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="flex flex-wrap gap-3">
                    {smartBlocks.map((block) => {
                      const IconComponent = block.icon;
                      return (
                        <Tooltip key={block.id}>
                          <TooltipTrigger asChild>
                            <Button
                              variant="outline"
                              onClick={() => addSmartBlock(block.id)}
                              className={`h-12 px-4 py-2 ${block.color} border-2 rounded-full transition-all duration-200 hover:shadow-md hover:scale-105 flex items-center gap-2 font-medium text-sm whitespace-nowrap`}
                            >
                              <IconComponent className="w-4 h-4 flex-shrink-0" />
                              {block.label}
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>
                            <p className="text-sm font-medium">{block.description}</p>
                          </TooltipContent>
                        </Tooltip>
                      );
                    })}
                  </div>
                </CardContent>
              </Card>

              {/* Learning Objectives */}
              <Card className="rounded-xl shadow-sm">
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm">Learning Objectives</CardTitle>
                </CardHeader>
                <CardContent className="space-y-2">
                  <div className="flex items-center gap-2">
                    <CheckCircle className="w-4 h-4 text-green-500" />
                    <span className="text-xs">Critical Thinking</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <CheckCircle className="w-4 h-4 text-green-500" />
                    <span className="text-xs">Evidence Synthesis</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="w-4 h-4 border-2 border-gray-300 rounded-full"></div>
                    <span className="text-xs text-gray-500">Academic Voice</span>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        </div>

        {/* Quick Actions */}
        <div className="text-center pt-6 border-t border-gray-200">
          <p className="text-gray-600 mb-4">Need more templates or writing support?</p>
          <Button variant="outline" size="lg" className="border-blue-300 text-blue-700 hover:bg-blue-50 rounded-xl">
            <Book className="w-5 h-5 mr-2" />
            Browse Template Library
            <ArrowRight className="w-5 h-5 ml-2" />
          </Button>
        </div>
      </div>
    </TooltipProvider>
  );
}
